package com.wn.pro.controller;

//import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
//import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
//import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @author yellow Docter
 * @date 2024-09-09
 * @desc 蜗牛创想：www.woniuxy.com
 *
 *   1、  @HystrixCommand(fallbackMethod = "errorFallback")  标记 远程调用失败的问题
 *
 *   2、  默认找 fallbackMethod 标记的方法  errorFallback
 *
 *   3、实现  errorFallback 的方法
 */
@RestController
@RequestMapping("test")
public class TestController {

    /**
     * 测试降级熔断
     */
//    @GetMapping("/find/{id}")
//    @HystrixCommand(fallbackMethod = "errorFallback",
//            commandProperties = {
//                    // 是否开启断路器
//                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED,value = "true"),
//                    // 请求错误率大于 50% 就启动熔断器
//                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE,value = "50"),
//                    // 默认10秒内访问接口达到20次，且错误率大于50%则打开断路器，触发熔断； 为了方便测试，这里修改请求数为10
//                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,value = "10"),
//                    //断路多久以后开始尝试是否恢复，默认5s
//                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS,value = "10000")
//            })
//    public String find(@PathVariable("id")Integer id) throws Exception {
//        if (id < 10) {
//            throw new Exception();
//        }
//        return "ok";
//    }

    /**
     * 测试降级熔断
     */
    @CircuitBreaker(name = "stu-pro-service", fallbackMethod = "errorFallback")
    @GetMapping("/find/{id}")
    public String find(@PathVariable("id")Integer id) throws Exception {
        if (id < 10) {
            throw new Exception();
        }
        return "ok";
    }

    // 降级方法
    public String errorFallback(Exception ex){
        String message = ex.getMessage();
        System.out.println("message = " + message);
        return "降级方法";
    }

    @GetMapping("/show")
    public String show() throws Exception {

        Random random = new Random();
        boolean b = random.nextBoolean();
        if (b){
            throw new Exception();
        }
        return "hello world show";
    }

}
